<template>
  <div class="app-container">
    <el-dialog
      v-dialogDrag
      title="资源分配"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <BossTree ref="resourceTree" :checked="checked" :resource="TreeData" :dialog-type="dialogType" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="closed">取 消</el-button>
        <el-button v-if="dialogType!='VIEW'" type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { getResourceListAPI } from '@/api/resourceAPI'
import { getRoleResourceAPI, assignResourceAPI } from '@/api/resourceAPI'
import BossTree from '@/components/TreeDisplay/index.vue'
export default {
  name: 'ResourceDialog',
  components: {
    BossTree
  },
  props: {
    dialogType: {
      type: String,
      default: 'VIEW'
    },
    rolesId: {
      type: Array,
      default: () => { return [] }
    }
  },
  data() {
    return {
      dialogVisible: false,
      TreeData: [],
      checked: []
    }
  },
  mounted() {
    this.initUI()
  },

  methods: {
    /**
     * 界面初始化操作
     */
    initUI() {
      this.checked = []
      this.TreeData = []
    },
    // 分配资源获取
    getTreeList() {
      // debugger
      getResourceListAPI(1000).then(Compos => {
        // debugger
        this.TreeData = Compos.data
      }).catch(error => {
        this.$message.error(error)
      })
    },
    // 查看资源数据获取
    getDefaultCheck(id) {
      getRoleResourceAPI(1000, id)
        .then(
          res => {
            const nodesId = []
            for (const node of res.data) {
              nodesId.push(node.id)
            }
            this.checked = nodesId
            // 获取树的数据
            this.getTreeList()
          }).catch(error => {
          this.$message.error(error)
        })
    },
    onShow(id) {
      this.dialogVisible = true
      if (this.dialogType === 'VIEW') { this.getDefaultCheck(id) } else this.getTreeList()
    },
    closed() {
      this.TreeData = []
      this.checked = []
      this.dialogVisible = false
    },
    /**
     * 对话框关闭处理函数
     * @param {*} done
     */
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.TreeData = []
          this.checked = []
          done()
        })
        .catch(_ => {})
    },
    /**
     * 表单提交函数
     */
    onSubmit() {
      const assignResourceData = {}
      assignResourceData.roleIds = []
      assignResourceData.resourceIds = this.$refs.resourceTree.getCheckedKey()
      for (const item of this.rolesId) { assignResourceData.roleIds.push(item.id) }
      assignResourceAPI(assignResourceData)
        .then((res) => {
          this.$message({
            message: '分配资源成功',
            type: 'success'
          })
          this.$emit('endEvent')
          this.closed()
        })
        .catch((erro) => {
          this.$message.error(erro)
        })
    }
  }
}
</script>

